package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Map;

public class Config {
    private final int port = 8080;
    private final String webRoot = "3_web_server/webroot";
    private final Map<String, Handler> handlerMap = new HashMap<>();

    private Config() {
        handlerMap.put("/", new DefaultHandler());
        handlerMap.put("/time", new TimeHandler());
        handlerMap.put("/echo", new EchoHandler());
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public int getPort() {
        return port;
    }

    public String getWebRoot() {
        return webRoot;
    }

    public Handler getHandler(String url) {
        // TODO: [222024321072031/黄璜] 实现 URL 精确匹配或基础路径匹配逻辑
        if (url == null || url.isEmpty() )
            return handlerMap.get("/");
        //去掉查询串，保证/echo?x=1能命中/echo
        int q = url.indexOf('?');
        if (q>=0)
            url = url.substring(0,q);
        //先精确匹配
        Handler h = handlerMap.get(url);
        if (h != null)
            return  h;
        //再做“基础路径匹配”（以注册路径为前缀）
        for (String base:handlerMap.keySet()){
            if (!"/".equals(base) && url.startsWith(base)){
                return handlerMap.get(base);
            }
        }
        return handlerMap.get("/"); //兜底

        //return handlerMap.get(url);
    }
}